package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Product;
import cn.wolfcode.trip.base.domain.ProductContent;
import cn.wolfcode.trip.base.mapper.ProductContentMapper;
import cn.wolfcode.trip.base.mapper.ProductMapper;
import cn.wolfcode.trip.base.query.QueryObject;
import cn.wolfcode.trip.base.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    //商品详情mapper
    @Autowired
    private ProductContentMapper productContentMapper;

    public PageInfo<Product> listAll(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        return new PageInfo<>(productMapper.selectForList(qo));
    }

    public void saveOrUpdate(Product entity) {
        if (entity.getId()!=null){
            productMapper.updateByPrimaryKey(entity);
            //content主键
            entity.getContent().setId(entity.getId());
            productContentMapper.updateByPrimaryKey(entity.getContent());
        }else {
            //新增商品时,设置创建时间
            entity.setCreateTime(new Date());
            productMapper.insert(entity);
            if (entity.getContent()!=null){
                //获取商品主键设置给商品详情主键
                entity.getContent().setId(entity.getId());
                productContentMapper.insert(entity.getContent());
            }
        }
    }

    public PageInfo queryProductByStatus(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Product> list = productMapper.selectForList(qo);
        return new PageInfo<>(list);
    }

    public PageInfo queryProductByCreateTime(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),qo.getOrderBy());
        return new PageInfo<>(productMapper.selectForList(qo));
    }

    public Product getProductById(Long id) {
        return productMapper.selectByPrimaryKey(id);
    }

    public ProductContent getProductContentById(Long id) {
        return productContentMapper.selectByPrimaryKey(id);
    }
}
